/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-08-09 17:31:48
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-11-20 10:42:31
 * @FilePath: \cxl-admin\src\pages\login\index.ts
 */
import { userStore } from '@/store/user.store'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { regMobile } from '@/utils'

/**
 * 定义账号字段
 */
interface accountInterface {
    name: string
    password: string
}

class LoginData {
    //用户仓库
    user: any

    //路由对象
    router: any

    //登录账号密码
    account: accountInterface | undefined

    //登录验证规则
    rules: FormRules
    constructor() {
        this.user = userStore()
        this.router = useRouter()
        this.user.setToken('')
        this.account = {
            name: '',
            password: ''
        }
        this.rules = {
            name: [
                {
                    required: true,
                    validator: this.userNameValidatePass,
                    trigger: 'blur'
                }
            ],
            password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
        }
    }
    /**
     * 账号是否验证通过，验证输入的账号是否是正确的手机号
     * @param rule
     * @param value
     * @param callback
     */
    userNameValidatePass(rule: any, value: any, callback: any) {
        if (value === '') {
            callback(new Error('请输入手机号码'))
        } else {
            console.log(value)
            regMobile(value) ? callback() : callback(new Error('手机号有误，请重新输入'))
        }
    }

    /**
     * 提交登录
     * @param formEl
     * @returns
     */
    async onSubmit(formEl: FormInstance | undefined) {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                this.user.login(this.account?.name, this.account?.password).then(
                    () => {
                        ElMessage({
                            type: 'success',
                            message: '欢迎登录长三角车生活系统'
                        })
                        this.router.push('/index')
                    },
                    (err: any) => {
                        console.log('err', err)
                        if (err.value === 30010) {
                            ElMessage.error('该账号已被禁用，请联系客服人员')
                        } else {
                            ElMessage.error(err.desc)
                        }
                    }
                )
            } else {
                console.log('error submit！', fields)
            }
        })
    }
}

export default LoginData
